package com.WebMentorPro.system.controller;

import com.WebMentorPro.system.annotation.AuthCheck;
import com.WebMentorPro.system.common.BaseResponse;
import com.WebMentorPro.system.common.DeleteRequest;
import com.WebMentorPro.system.common.ErrorCode;
import com.WebMentorPro.system.common.ResultUtils;
import com.WebMentorPro.system.constant.UserConstant;
import com.WebMentorPro.system.exception.BusinessException;
import com.WebMentorPro.system.exception.ThrowUtils;
import com.WebMentorPro.system.model.dto.activity.*;
import com.WebMentorPro.system.model.entity.Activity;
import com.WebMentorPro.system.model.entity.SignIn;
import com.WebMentorPro.system.model.entity.Teacher;
import com.WebMentorPro.system.model.entity.User;
import com.WebMentorPro.system.model.vo.ActivityVO;
import com.WebMentorPro.system.model.vo.LoginUserVO;
import com.WebMentorPro.system.service.ActivityService;
import com.WebMentorPro.system.service.SignInService;
import com.WebMentorPro.system.service.TeacherService;
import com.WebMentorPro.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 异科导师活动接口
 *
 * @author bianxinyao
 */
@RestController
@RequestMapping("/activity")
@Slf4j
@Api(tags = {"异科导师活动接口"})
public class ActivityController {

    @Resource
    private UserService userService;

    @Resource
    private ActivityService activityService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private SignInService signinService;

    // region 登录相关

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login/user")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    /**
     * 获取当前登录异科导师
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login/teacher")
    public BaseResponse<Teacher> getLoginTeacher(HttpServletRequest request) {
        Teacher teacher = teacherService.getLoginTeacher(request);
        return ResultUtils.success(teacher);
    }

    // endregion

    // region 增删改查

    /**
     * 创建活动
     *
     * @param activityAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建活动(仅异科导师)")
    public BaseResponse<Long> addActivity(@RequestBody ActivityAddRequest activityAddRequest, HttpServletRequest request) {
        if (activityAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        ThrowUtils.throwIf(activityAddRequest.getTitle().length() > 50, ErrorCode.PARAMS_ERROR, "请求参数过长");
        if (StringUtils.isBlank(activityAddRequest.getTitle())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        ThrowUtils.throwIf(activityAddRequest.getContent().length() > 500, ErrorCode.PARAMS_ERROR, "活动内容过长");
        ThrowUtils.throwIf(activityAddRequest.getAddress().length() > 50, ErrorCode.PARAMS_ERROR, "活动地址过长");
        ThrowUtils.throwIf(activityAddRequest.getTags().length() > 50, ErrorCode.PARAMS_ERROR, "活动标签过长");
        Long id = teacherService.getLoginTeacher(request).getId();
        ThrowUtils.throwIf(id == null, ErrorCode.NOT_LOGIN_ERROR, "用户未登录或者没有权限创建活动");
        Activity activity = new Activity();
        BeanUtils.copyProperties(activityAddRequest, activity);
        activity.setTeacherId(Math.toIntExact(id));
        boolean result = activityService.save(activity);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "活动创建失败");
        return ResultUtils.success(activity.getId());
    }

    /**
     * 删除活动（仅管理员）
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除活动（仅管理员）")
    public BaseResponse<Boolean> deleteActivity(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = activityService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "活动删除失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新活动
     *
     * @param activityUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("更新活动")
    public BaseResponse<Boolean> updateActivity(@RequestBody ActivityUpdateRequest activityUpdateRequest, HttpServletRequest request) {
        if (activityUpdateRequest == null || activityUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = teacherService.getLoginTeacher(request).getId();
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", activityUpdateRequest.getId());
        Activity oldActivity = activityService.getOne(queryWrapper);
        ThrowUtils.throwIf(oldActivity == null, ErrorCode.NOT_FOUND_ERROR, "活动不存在");
        if (activityUpdateRequest.getTitle() == null || activityUpdateRequest.getContent().equals("")) {
            activityUpdateRequest.setTitle(oldActivity.getTitle());
        }
        if (activityUpdateRequest.getContent() == null || activityUpdateRequest.getContent().equals("")) {
            activityUpdateRequest.setContent(oldActivity.getContent());
        }
        if (activityUpdateRequest.getAddress() == null || activityUpdateRequest.getAddress().equals("")) {
            activityUpdateRequest.setAddress(oldActivity.getAddress());
        }
        if (activityUpdateRequest.getTags() == null || activityUpdateRequest.getTags().equals("")) {
            activityUpdateRequest.setTags(oldActivity.getTags());
        }
        if (activityUpdateRequest.getStartTime() == null || activityUpdateRequest.getStartTime().equals("")) {
            activityUpdateRequest.setStartTime(oldActivity.getStartTime());
        }
        if (activityUpdateRequest.getEndTime() == null || activityUpdateRequest.getEndTime().equals("")) {
            activityUpdateRequest.setEndTime(oldActivity.getEndTime());
        }
        ThrowUtils.throwIf(activityUpdateRequest.getTitle().length() > 50, ErrorCode.PARAMS_ERROR, "活动名称过长");
        ThrowUtils.throwIf(activityUpdateRequest.getContent().length() > 500, ErrorCode.PARAMS_ERROR, "活动内容过长");
        ThrowUtils.throwIf(activityUpdateRequest.getAddress().length() > 50, ErrorCode.PARAMS_ERROR, "活动地址过长");
        ThrowUtils.throwIf(activityUpdateRequest.getTags().length() > 50, ErrorCode.PARAMS_ERROR, "活动标签过长");

        Activity activity = new Activity();
        BeanUtils.copyProperties(activityUpdateRequest, activity);


        boolean result = activityService.updateById(activity);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "活动更新失败");
        return ResultUtils.success(result);
    }

    /**
     * 分页获取全部活动（仅管理员）
     *
     * @param activityQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "分页获取全部活动（仅管理员）")
    public BaseResponse<Page<ActivityVO>> listActivityByPage(@RequestBody ActivityQueryRequest activityQueryRequest, HttpServletRequest request) {
        long current = activityQueryRequest.getCurrent() == 0 ? 1 : activityQueryRequest.getCurrent();
        long size = activityQueryRequest.getPageSize() == 0 ? 10 : activityQueryRequest.getPageSize();

        Page<ActivityVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<ActivityVO> pageComments = activityService.getQueryWrapper(pageParam, activityQueryRequest);

        return ResultUtils.success(pageComments);
    }

    /**
     * 分页获取自己创建的活动
     *
     * @param activityQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/my")
    @ApiOperation("分页获取异科导师创建的活动")
    public BaseResponse<Page<ActivityVO>> listActivityVOByPage(@RequestBody ActivityQueryRequest activityQueryRequest, HttpServletRequest request) {
        Long id = teacherService.getLoginTeacher(request).getId();
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Teacher one = teacherService.getOne(queryWrapper);
        if (one == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        String teacherName = one.getTeacherName();
        long current = activityQueryRequest.getCurrent() == 0 ? 1 : activityQueryRequest.getCurrent();
        long size = activityQueryRequest.getPageSize() == 0 ? 10 : activityQueryRequest.getPageSize();

        Page<ActivityVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<ActivityVO> pageComments = activityService.getQueryWrapperByMy(pageParam, activityQueryRequest, teacherName);

        return ResultUtils.success(pageComments);
    }

    /**
     * 分页获取学生需要参加的活动
     *
     * @param activityQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/student")
    @ApiOperation("分页获取学生需要参加的活动")
    public BaseResponse<Page<ActivityVO>> listActivityVOByStudent(@RequestBody ActivityQueryRequestByStudent activityQueryRequest, HttpServletRequest request) {
        Long id = userService.getLoginUser(request).getId();
        if (id == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        User one = userService.getOne(queryWrapper);
        if (one == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        int teacherId = one.getTeacherId();
        if (teacherId == 0) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未绑定导师");
        }
        QueryWrapper<Activity> queryActivity = new QueryWrapper<>();
        queryActivity.eq("teacherId", teacherId);
        // 统计活动的数量
        long total = activityService.count(queryActivity);
        if (total == 0) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "异科导师没有创建活动");
        }
        long current = activityQueryRequest.getCurrent() == 0 ? 1 : activityQueryRequest.getCurrent();
        long size = activityQueryRequest.getPageSize() == 0 ? 10 : activityQueryRequest.getPageSize();

        Page<ActivityVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<ActivityVO> pageComments = activityService.getQueryByStudent(pageParam, activityQueryRequest, teacherId);

        return ResultUtils.success(pageComments);
    }

    /**
     * 活动签到请求
     *
     * @param signInAddRequest
     * @param request
     * @return
     */
    @PostMapping("/signIn")
    @ApiOperation("活动签到请求")
    public BaseResponse<Date> activitySignIn(@RequestBody SignInAddRequest signInAddRequest, HttpServletRequest request) {
        Long id = userService.getLoginUser(request).getId();
        if (id == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
        }

        SignIn signIn = new SignIn();

        QueryWrapper<Activity> queryActivity = new QueryWrapper<>();
        queryActivity.eq("id", signInAddRequest.getId());
        Activity activity = activityService.getOne(queryActivity);

        if (activity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "活动不存在");
        }
        if (activity.getStartTime().after(new Date())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "活动还没有开始");
        }
        if (activity.getEndTime().before(new Date())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "活动已经结束");
        }
        QueryWrapper<SignIn> querySignIn = new QueryWrapper<>();
        querySignIn.eq("studentId", id).eq("id", signInAddRequest.getId());
        SignIn one = signinService.getOne(querySignIn);
        if (one != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "已经签到了，请勿重复签到");
        }

        signIn.setStudentId(id);
        signIn.setTeacherId(activity.getTeacherId());
        signIn.setSignInTime(new Date());
        signIn.setLocation(signInAddRequest.getAddress());
        signIn.setNotes(signInAddRequest.getNotes());
        signinService.save(signIn);

        return ResultUtils.success(signIn.getSignInTime());
    }

    // endregion
}
